//
// Created by 33145 on 2023/4/3.
//

#include "protocol.h"
#include "sylar/util.h"

namespace chat {

  ChatMessage::ptr ChatMessage::Create(const std::string& s) {
    ChatMessage::ptr rt(new ChatMessage);
    int n = s.size();
    std::string key{};
    std::string value{};
    for (int i = 0; i < n; i++) {
      if (s[i] == '"') {
        int k = i;
        while(k == i || s[k] != '"') {
          ++k;
        }
        key = s.substr(i + 1, k - i - 1);
        ++k;
        while(s[k] != '"') {
          ++k;
        }
        int t = k;
        while(t == k || s[t] != '"') {
          ++t;
        }
        value = s.substr(k + 1, t - k - 1);
        rt->m_datas[key] = value;
        key.clear();
        value.clear();
        i = t + 1;
      }
    }
    return rt;
    /*
    Json::Value json;
    // std::cout << "--------------------------" << std::endl;
    if(!sylar::JsonUtil::FromString(json, v)) {
      // std::cout << "--------------------------" << std::endl;
      return nullptr;
    }
    // std::cout << "--------------------------" << std::endl;
    ChatMessage::ptr rt(new ChatMessage);
    // std::cout << "--------------------------" << std::endl;
    auto names = json.getMemberNames();
    // std::cout << "--------------------------" << std::endl;
    for(auto& i : names) {
      rt->m_datas[i] = json[i].asString();
    }
    // std::cout << "--------------------------" << std::endl;
    return rt;*/
  }

  ChatMessage::ChatMessage() {
  }

  std::string ChatMessage::get(const std::string& name) {
    auto it = m_datas.find(name);
    return it == m_datas.end() ? "" : it->second;
  }

  void ChatMessage::set(const std::string& name, const std::string& val) {
    m_datas[name] = val;
  }

  std::string ChatMessage::toString() const {
    Json::Value json;
    for(auto& i : m_datas) {
      json[i.first] = i.second;
    }
    return sylar::JsonUtil::ToString(json);
  }

  std::string ChatMessage::myToString() const {
    std::string res = "";
    int cnt = 0;
    int n = m_datas.size();
    for (auto [key, value] : m_datas) {
      res.append("\"" + key + "\"" + ":\"" + value + "\"");
      if (++cnt < n) {
        res.append(",");
      }
    }
    return "{" + res + "}";
  }

}
